import {router,addRoutes} from '~/router'
import { getToken } from "~/composables/auth";
import { success,showFullLoading,hideFullLoading } from "~/composables/util";
import store from './store/index'



//全局前置守卫

let hasGetInfo =false

router.beforeEach(async(to, from,next) => {
    showFullLoading()
    const token=getToken()
    //没有登录，就跳转登录页
    if(!token&&to.path !='/Login'){
        success('请先登录','error')
        return next({path:"/Login"})
    }
    //防止重复登录
    if(token&&to.path =='/Login'){
        success('请勿重复登录','error')
        return next({path:from.path?from.path:'/'})
    }
    //如果用户登录了，就自动获取用户信息，并存储vuex
    let hasNewRoutes =false
    if(token && !hasGetInfo){
       let {menus}= await store.dispatch("getinfo")
       hasGetInfo=true
       //动态添加路由
       hasNewRoutes=addRoutes(menus)
    }

    //设置页面标题
    let title=(to.meta.title?to.meta.title:'')+"-四岁项目后台"
    document.title=title
    hasNewRoutes?next(to.fullPath):next()
  })

  //全局后置守卫
  router.afterEach((to, from) => {
    hideFullLoading()
  })
  